package com.cn.shiro;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.cn.shiro.entity.UUser;
import com.cn.shiro.service.PermissionService;
import com.cn.shiro.service.UUserService;

/**
 * 
 * @author lvin
 *
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private UUserService uUserService;

    @Resource
    private PermissionService permissionService;

    
    public MyShiroRealm() {
		super();
	}
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UUser user= (UUser) SecurityUtils.getSubject().getPrincipal();//User{id=1, username='admin', password='3ef7164d1f6167cb9f2658c07d3c2f0a', enable=1}
        Set<String> resourcesList = permissionService.findPermissionByUserId(user.getId());
        // 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for(String resources: resourcesList){
            info.addStringPermission(resources);
        }
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        UUser user = uUserService.findUserByEmail(username);
        if(user==null){
        	throw new UnknownAccountException();
        }else if (0==user.getStatus()) {
            throw new LockedAccountException(); // 帐号锁定
        }else {
        	Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String format = sdf.format(date);
			Date parse = new Date();
			try {
				parse = sdf.parse(format);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
			}
			user.setLastLoginTime(parse);
			uUserService.updateByPrimaryKeySelective(user);
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPswd(),getName());
        // 当验证都通过后，把用户信息放在session里
        /*Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("userSession", user);
        session.setAttribute("userSessionId", user.getId());*/
        return authenticationInfo;
    }

    /**
     * 指定principalCollection 清除
     */
  /*  public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {

        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }
*/
}
